package cn.lyq.card.base

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import cn.lyq.card.R
import cn.lyq.card.utils.QMUIStatusBarHelper
import com.blankj.utilcode.util.BusUtils

abstract class BaseFg : Fragment() {

    var vTop: View? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return LayoutInflater.from(requireContext()).inflate(getLayoutId(), null, false).apply {
            vTop = findViewById(R.id.vTop)
            BusUtils.register(
                this@BaseFg
            )
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        initVM()
        initData()
        initView(view)
        initListener(view)
        initObserver()
    }

    override fun onStart() {
        super.onStart()
        QMUIStatusBarHelper.getStatusbarHeight(requireContext())
            .takeIf { it > 0 }?.also {
                vTop?.apply {
                    layoutParams.height = it
                    layoutParams = layoutParams
                }
            }
    }

    abstract fun getLayoutId(): Int

    open fun initVM() {}

    open fun initData() {}

    open fun initView(view: View) {}

    open fun initListener(view: View) {}

    open fun initObserver() {
    }

    override fun onDestroy() {
        super.onDestroy()
        BusUtils.unregister(this)
    }

    fun <T : ViewModel> getVM(
        vm: Class<T>,
        factory: ViewModelProvider.Factory = ViewModelProvider.NewInstanceFactory()
    ) = ViewModelProvider(this, factory).get(vm)

    fun <T : ViewModel> getVMActivity(
        vm: Class<T>,
        factory: ViewModelProvider.Factory = ViewModelProvider.NewInstanceFactory()
    ) = ViewModelProvider(requireActivity(), factory).get(vm)

    fun startActivity(clazz: Class<*>) {
        startActivity(Intent(requireContext(), clazz))
    }

    override fun onDestroyView() {
        super.onDestroyView()
        BusUtils.unregister(this)
    }


    fun showLoading(){}

    fun dismissLoading(){

    }
}